package com.colin.controller;

import com.colin.pojo.PageBean;
import com.colin.pojo.ShangChuanData;
import com.colin.pojo.User;
import com.colin.service.ShangChuanDateService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Controller

@RequestMapping ("ShangChuanDate")
public class ShangChuanDateController {
    @Autowired
    ShangChuanDateService shangChuanDateService;

    @RequestMapping ("find")
    public String find (Integer currentPage,HttpSession session) {
        PageBean<ShangChuanData> pageBeanData = shangChuanDateService.findBlogByPageUplodData(currentPage);
        int number1 = shangChuanDateService.count();//计算上传多少个文件;
        session.setAttribute("pageBeanData", pageBeanData);
        session.setAttribute("number1",number1);
        return "redirect:/web/tiaoZhuan6";
    }
    @RequestMapping ("download")
    public String download (Integer id , HttpServletResponse response) throws IOException {
        ShangChuanData data= shangChuanDateService.find(id);
        String path = "C:\\Users\\ASUS\\Desktop\\mrp-ssm\\web\\file\\"+data.getF_name(); //默认认为文件在当前项目的根目录
        FileInputStream fis = new FileInputStream(path);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment; filename="+data.getF_name());
        ServletOutputStream out = response.getOutputStream();
        byte[] bt = new byte[1024];
        int length = 0;
        while((length=fis.read(bt))!=-1){
            out.write(bt,0,length);
        }
        out.close();
        return "";
    }
    @RequestMapping ("/doUpload")
    public String doUpload(MultipartFile file, ShangChuanData shangChuanData, HttpSession session) throws IOException {
        if (file!=null) {
            FileUtils.copyInputStreamToFile(file.getInputStream(),
                    new File("C:\\Users\\ASUS\\Desktop\\mrp-ssm\\web\\file", file.getOriginalFilename()));
//              private int f_id;
            //    private String f_name;
            //    private String f_type;
            //    private String f_path;
            //    private String f_actor;
            User user= (User) session.getAttribute("user");
            String fileName = file.getOriginalFilename();
            shangChuanData.setF_name(fileName);
            shangChuanData.setF_path("/file/"+fileName);
            shangChuanData.setF_actor(user.getName());
            shangChuanDateService.insert(shangChuanData);

        }
        return "redirect:/ShangChuanDate/find?currentPage=1";
    }
}
